/*
 * FreeModbus Libary: RT-Thread Port
 * Copyright (C) 2013 Armink <armink.ztl@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * File: $Id: porttimer.c,v 1.60 2013/08/13 15:07:05 Armink $
 */

/* ----------------------- Platform includes --------------------------------*/
#include "port.h"
#include "main.h"
/* ----------------------- Modbus includes ----------------------------------*/
#include "mb.h"
#include "mbport.h"



extern TIM_HandleTypeDef htim2;


/* ----------------------- static functions ---------------------------------*/
static void prvvTIMERExpiredISR(void);

/* ----------------------- Start implementation -----------------------------*/
BOOL xMBPortTimersInit(USHORT usTim1Timerout50us)
{
	
	MX_TIM2_Init(usTim1Timerout50us);
    return TRUE;
}

void vMBPortTimersEnable()
{
    // 开启定时器，计算是否超时

	__HAL_TIM_CLEAR_IT(&htim2, TIM_IT_UPDATE);  // 清除中断标志位
    __HAL_TIM_ENABLE_IT(&htim2, TIM_IT_UPDATE); //开启定时器自动更新中断
	__HAL_TIM_SET_COUNTER(&htim2, 0x0000);  // 设置计数器的值为0
	__HAL_TIM_ENABLE(&htim2);   // 开启定时器中断
   
    
}

void vMBPortTimersDisable()
{   
	__HAL_TIM_DISABLE(&htim2);    // 关闭定时器中断
	__HAL_TIM_SET_COUNTER(&htim2, 0x0000);  // 设置计数器的值为0
	__HAL_TIM_DISABLE_IT(&htim2, TIM_IT_UPDATE); //关闭定时器自动更新中断
	__HAL_TIM_CLEAR_IT(&htim2, TIM_IT_UPDATE);  // 清除中断标志位
}

void prvvTIMERExpiredISR(void)
{
    (void)pxMBPortCBTimerExpired();
}



void TIM2_IRQHandler(void)
{

  HAL_TIM_IRQHandler(&htim2);
  if(__HAL_TIM_CLEAR_FLAG(&htim2, TIM_FLAG_UPDATE) != RESET)
  {
    prvvTIMERExpiredISR();
  	__HAL_TIM_CLEAR_FLAG(&htim2, TIM_FLAG_UPDATE);  // 清除中断标志位
  }
  /* USER CODE BEGIN TIM2_IRQn 1 */

  /* USER CODE END TIM2_IRQn 1 */
}


